import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'
import LoginApi from '@/api/login.js'
import storage from '@/utils/storage'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
	const token = ref('')
	const userInfo = ref({})

	const login = async ({
		loginCode,
		phoneCode
	}) => {
		const result = await LoginApi.auth({
			loginCode,
			phoneCode
		})
		if (result.code === 200) {
			token.value = result.data.token
			setToken(token.value)
			return true
		}
		return false
	}

	const getUserInfo = async () => {
		const result = await LoginApi.userInfo()
		if (result.code === 200) {
			userInfo.value = result.data
			storage.set('userInfo', result.data)
			return userInfo.value
		}
		return
	}

	const logout = async() => {
		await LoginApi.logout()
		token.value = ''
		userInfo.value = {}
		removeToken()
		storage.remove('userInfo')
	}

	return {
		token,
		login,
		userInfo,
		getUserInfo,
		logout
	}
})